/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-10-13 22:12:22
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-10-15 16:48:45
 * @FilePath: /Learn/udp/UdpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include"Terminal.hpp"
#include <iostream>
#include <cstdlib>
#include <string>
#include<cstring>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<pthread.h>
#include <arpa/inet.h>
using namespace std;
void Usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverip serverport\n"
              << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void*recv_message(void*args)
{
    OpenTerminal();
    ThreadData *td=static_cast<ThreadData*>(args);
    char buffer[1024];

    while(1)
    {
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        ssize_t s=recvfrom(td->sockfd,buffer,1023,0,(sockaddr*)&temp,&len);
        if(s>0)
        {
            buffer[s]=0;
            cerr<<buffer<<endl;
        }
    }
}

void*send_message(void*args)
{
    ThreadData *td=static_cast<ThreadData*>(args);
    string message;
    socklen_t len = sizeof(td->server);
    string welcome=td->serverip;
    welcome+="comming...";
    sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (sockaddr *)&(td->server), len);
    while(1)
    {
        cout << "Please Enter@ ";
        getline(cin, message);
        // 1.数据 2.给谁发
        //cout<<message<<endl;
        sendto(td->sockfd, message.c_str(), message.size(), 0, (sockaddr *)&(td->server), len);
    }
}
//./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);//主机转网络
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd= socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socket error" << endl;
        return 1;
    }

    td.serverip=serverip;
    pthread_t recvr,sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);
    close(td.sockfd);
    return 0;
}